package cn.myapps.demospringsecurity.service.impl;

import cn.myapps.demospringsecurity.entity.LoginUser;
import cn.myapps.demospringsecurity.entity.User;
import cn.myapps.demospringsecurity.entity.UserDepartmentRoleSet;
import cn.myapps.demospringsecurity.mapper.UserDepartmentRoleSetMapper;
import cn.myapps.demospringsecurity.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 用户信息校验
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper mapper;
    @Autowired
    private UserDepartmentRoleSetMapper rolemapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = mapper.selectById(username);
        LambdaQueryWrapper<UserDepartmentRoleSet> ew = new LambdaQueryWrapper<>();
        ew.eq(UserDepartmentRoleSet::getUserid, username);
        List<UserDepartmentRoleSet> roles = rolemapper.selectList(ew);
        // 将数据库中的角色转换为 Spring Security 的 GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (UserDepartmentRoleSet role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + roles));
        }
        System.out.println("user+++" + user);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名为空");
        }
        return new LoginUser(user, authorities);
    }

    // 密码编码器（BCrypt）
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
